package org.oneblog.service.tools;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.media.jai.PlanarImage;

import org.apache.commons.io.IOUtils;

import com.alibaba.simpleimage.ImageWrapper;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleParameter.Algorithm;
import com.alibaba.simpleimage.render.WatermarkParameter;
import com.alibaba.simpleimage.util.ImageDrawHelper;
import com.alibaba.simpleimage.util.ImageReadHelper;
import com.alibaba.simpleimage.util.ImageScaleHelper;

public class ImageUtilsForGroup {
    public static Integer getHeight(Integer w, Integer h, Integer width) {

        return h * width / w;
    }

    public static Integer getWidth(Integer w, Integer h, Integer height) {
        return w * height / h;
    }

    //这里不能关闭is，交给上层处理
    public static InputStream circleImg(BufferedImage bi1) throws IOException {
        long b = System.currentTimeMillis();
        InputStream is = null;
        ByteArrayOutputStream os = null;
        try {
            BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_ARGB);

            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());

            System.out.println("创建空白透明图片 " + (System.currentTimeMillis() - b));
            b = System.currentTimeMillis();
            Graphics2D g2 = image.createGraphics();
            image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
            g2 = image.createGraphics();
            g2.setComposite(AlphaComposite.Clear);
            g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
            g2.setClip(shape);
            

            System.out.println("将原始图片作为圆形素材写入空白图片 " + (System.currentTimeMillis() - b));
            b = System.currentTimeMillis();
            // 使用 setRenderingHint 设置抗锯齿
            g2.drawImage(bi1, 0, 0, null);
            g2.dispose();
            os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            is = new ByteArrayInputStream(os.toByteArray());

            System.out.println("将新图片写入到输出流 " + (System.currentTimeMillis() - b));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(os);
        }
        
        return is;
    }

    public static ImageWrapper placeImage(ImageWrapper dist, BufferedImage src, int x, int y, int width, int height, boolean isCircle, boolean isScaleRate) throws Exception {
        ImageWrapper waterWrapper = null;
        InputStream is = null;
        
        try {
            long b1 = System.currentTimeMillis();
            if (isCircle) {
                is = circleImg(src);
                waterWrapper = ImageReadHelper.read(is);
            } else {
                waterWrapper = new ImageWrapper(src);
            }
            System.out.println("读取图片资源，是否圆形转换（" + isCircle + "） " + (System.currentTimeMillis() - b1));

            // 缩放src图片
            int w = waterWrapper.getWidth();
            int h = waterWrapper.getHeight();
            // 1.缩放
            ScaleParameter scaleParam = new ScaleParameter(w, h, Algorithm.LANCZOS); // 缩放参数
            float srcRatio = (float) w / h;
            float dstRatio = (float) width / height;// 源宽高比和目标宽高比
            
            if(isScaleRate) {//等比缩放

                if (w < width && h < height) {// 如果图片宽和高都小于目标图片则不做缩放处理
                    scaleParam = new ScaleParameter(w, h, Algorithm.LANCZOS);
                } else if (srcRatio >= dstRatio) {
                    int newHeight = getHeight(w, h, width);
                    scaleParam = new ScaleParameter(width + 1, newHeight + 1, Algorithm.LANCZOS);
                } else if (srcRatio < dstRatio) {
                    int newWidth = getWidth(w, h, height);
                    scaleParam = new ScaleParameter(newWidth + 1, height, Algorithm.LANCZOS);
                }
            } else {//直接缩放
                scaleParam = new ScaleParameter(width, height, Algorithm.LANCZOS);
            }
            PlanarImage planrImage = ImageScaleHelper.scale(waterWrapper.getAsPlanarImage(), scaleParam);
            waterWrapper = new ImageWrapper(planrImage);

            WatermarkParameter param = new WatermarkParameter(waterWrapper, 1, x, y);
            
            b1 = System.currentTimeMillis();
            BufferedImage bufferedImage = ImageDrawHelper.drawWatermark(dist.getAsBufferedImage(), param);
            System.out.println("根据转换参数生成新的图片资源 " + (System.currentTimeMillis() - b1));

            dist = new ImageWrapper(bufferedImage);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
        }

        return dist;
    }

    static ImageWrapper locateTxt(BufferedImage src, float radio, List<GroupTextConf> confs) throws IOException, SimpleImageException {
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            Graphics2D g2 = src.createGraphics();

            for(GroupTextConf conf : confs) {
                int type = conf.getType();
                g2.setColor(conf.getColor());
                if( type == 1) {
                    g2.setFont(conf.getFont());
                    g2.drawString(conf.getText(), conf.getXWithRadio(radio), conf.getYWithRadio(radio));
                    //删除线
                    
                    if(conf.getDelLine()) {
                        int h = 744;
                        g2.drawLine(510, h, 610, h);
                    }
                } else if(type == 2) {
                    //矩形
                    g2.fillRect(conf.getXWithRadio(radio), conf.getYWithRadio(radio), 
                            conf.getWidthWithRadio(radio), conf.getHeightWithRadio(radio));
                }
            }

            g2.dispose();
            bos = new ByteArrayOutputStream();
            long b = System.currentTimeMillis();
            ImageIO.write(src, "png", bos);
            System.out.println("ImageIO.write " + (System.currentTimeMillis() - b));
            
            b = System.currentTimeMillis();
            is = new ByteArrayInputStream(bos.toByteArray());
            ImageWrapper iw = ImageReadHelper.read(is);
            System.out.println("bos to inputStream " + (System.currentTimeMillis() - b));
            
            return iw;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(is);
        }
        return null;
    }

}
